package com.quyeying.controller;

import com.quyeying.config.scheduling.CronTaskRegistrar;
import com.quyeying.config.scheduling.SchedulingRunnable;
import com.quyeying.service.SysJobService;
import com.quyeying.utils.result.R;
import com.quyeying.entity.SysJob;
import com.quyeying.utils.result.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 定时任务表 前端控制器
 * </p>
 *
 * @author skx
 * @since 2021-08-09
 */
@RestController
@RequestMapping("/job")
public class SysJobController {

    @Autowired
    SysJobService sysJobService;
    @Autowired
    CronTaskRegistrar cronTaskRegistrar;

    /**
     * 新增定时任务
     */
    @PostMapping("/addCronTask")
    public R addCronTask(@RequestBody SysJob sysJob) {

        boolean success = sysJobService.save(sysJob);
        if (!success) {
            return R.error(ResultEnum.SYSTEM_ERROR);
        } else {
            if (sysJob.getJobStatus().equals(1)) {
                SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
                cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
            }
        }

        return R.success();
    }

    /**
     * 修改定时任务
     */
    @PostMapping("/editCronTask")
    public R editCronTask(@RequestBody SysJob sysJob) {

        SysJob job = sysJobService.getById(sysJob.getId());

        //先移除再添加
        if (job.getJobStatus().equals(1)) {
            SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
        }

        sysJobService.updateById(sysJob);

        if(sysJob.getJobStatus().equals(1)) {
            SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
            cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
        }
        return R.success();
    }

    /**
     * 删除定时任务
     */
    @PostMapping("/removeCronTask/{jobId}")
    public R removeCronTask(@PathVariable("jobId") Integer jobId) {

        SysJob sysJob = sysJobService.getById(jobId);

        if (sysJob.getJobStatus().equals(1)) {

            SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
            sysJobService.removeById(jobId);
        }

        return R.success();
    }
}
